import java.awt.*;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;
public class Missile {
	public static final int XSPEED = 10;
	public static final int YSPEED = 10;

	public static final int WIDTH = 10;
	public static final int HEIGHT = 10;
	private boolean live = true;
	private TankClient tc; 
	private int x, y;
	Tank.Direction dir;
	boolean good=true;
	public boolean isLive() {
		return live;
		}

	public Missile(int x, int y, Tank.Direction dir,TankClient tc,boolean g) {
		this.x = x;
		this.y = y;
		this.dir = dir;
		this.tc = tc;
		this.good=g;
	}

	public void draw(Graphics g) {
		//如果没有活着，就从容器中去掉，并且不再画了
		if(!live) {
			tc.missiles.remove(this); 
			return;
			}

		Color c = g.getColor();
		g.setColor(Color.BLACK);
		g.fillOval(x, y, WIDTH, HEIGHT);
		g.setColor(c);

		move();
	}

	private void move() {
		switch (dir) {
		case L:
			x -= XSPEED;
			break;
		case LU:
			x -= XSPEED;
			y -= YSPEED;
			break;
		case U:
			y -= YSPEED;
			break;
		case RU:
			x += XSPEED;
			y -= YSPEED;
			break;

		case R:
			x += XSPEED;
			break;
		case RD:
			x += XSPEED;
			y += YSPEED;
			break;
		case D:
			y += YSPEED;
			break;
		case LD:
			x -= XSPEED;
			y += YSPEED;
			break;
		}
		if(x < 0 || y < 0 || x > TankClient.GAME_WIDTH || y >
		 

		TankClient.GAME_HEIGHT) {
		live = false;
		tc.missiles.remove(this);
		}

	}
	public boolean collidesWithTank(Tank t) {
		//如果子弹活着，子弹与坦克相碰，坦克活着，
		//子弹与坦克不是一伙的，那么这样才开火
		if(this.live && this.getRect().intersects(t.getRect()) 
				&& t.isLive() && this.good != t.isGood()) {
		if(t.isGood()) {
		 

		t.setLife(t.getLife() - 20);
		if(t.getLife() <= 0) { 
			t.setLive(false);
		}else {
			t.setLive(true);
			this.live = false;
			Explode e = new Explode(x, y, tc);
			tc.explodes.add(e);
			return true;
		} 
		}
		
		}
		return false;
		}

	//getRect()可以正好拿到包在坦克外面的方块
	public Rectangle getRect() {
	return new Rectangle(x, y, WIDTH, HEIGHT);
	}
	public boolean hitTanks(List<Tank> tanks) {
		for(int i = 0; i < tanks.size(); i++) {
		if(hitTank(tanks.get(i))) {	
		if(tanks.get(i).isGood()&&tanks.get(i).isLive()) {
			
		}else {
			tanks.remove(i);}
		return true;
		}
		}
		return false;
		}
	public boolean hitWall(Wall w) {
		if(this.live &&
		this.getRect().intersects(w.getRect())) {
		this.live = false; 
		return true;
		}
		return false;
		}

	public boolean hitTank(Tank t) { 
		if(this.getRect().intersects(t.getRect()) &&
			t.isLive()&& this.good != t.isGood())  {
			if(t.isGood()) {
				t.setLife(t.getLife() - 20);
				t.setLive(true);
				
				if(t.getLife() <= 0) { 
					t.setLive(false);					 					
				}
				} else {
					t.setLive(false);				
				}

			Explode e = new Explode(t.getX(), t.getY(), tc); 
			tc.explodes.add(e);
			this.live = false; 
			
			return true;

			}
			return false;
			}


}
